package android.kryten.service.impl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.json.JSONArray;
import org.json.JSONObject;

import android.kryten.model.Document;
import android.kryten.service.DocumentService;
import android.util.Log;

public class DocumentServiceImpl implements DocumentService {

	private static final String TAG = "DOCUMENT_SERVICE";
	private final String URL_GET_ALL = "opensocial/ui/documents/ajaxlist/";
	private final String URL_GET_MY = "";
	public HttpClient client;
	
	public List<Document> getAllDocuments() {
		List<Document> result = new ArrayList<Document>();
        try {
        	
        	HttpPost req = new HttpPost("http://10.0.2.2:8080/" + URL_GET_ALL);
          	            
            HttpResponse resp = client.execute(req);
            if (resp.getStatusLine().getStatusCode() != 200) {
                Log.e(TAG, "Bad server response code:"+resp.getStatusLine().getStatusCode());
                //there we can return null, or throw an exception, because nothing better cannot be done
                return null;
            }
           
            StringBuilder sb = new StringBuilder();
            
            BufferedReader br = new BufferedReader(new InputStreamReader(resp.getEntity().getContent(), "UTF-8"));
            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            
            String json = sb.toString();
            
            JSONObject container = new JSONObject(json);
            	            
            JSONArray documents = container.getJSONArray("items");
            for (int i = 0; i < documents.length(); i++) {
                JSONObject d = documents.getJSONObject(i);
                
                Document document = new Document();
                
                document.setTopicType(d.getString("topicType"));
//                document.setAuthor(d.getString("author"));
                                
                result.add(document);
            }	                        
            
        } catch (Exception e) {
            Log.e(TAG, "Unable to retrieve obejctives", e);
        }
        	        
        return result;
	}
	
}
